<template>
	<view class="PAudio">
		<!-- 导航栏 -->
		<u-navbar
			title-color="#fff"
			back-icon-color="#ffffff"
			is-back="true"
			:background="background"
			:back-text-style="{ color: '#fff' }"
			title="发布语音"
			back-icon-name="nav-back"
			back-text="返回"
		>
			<view class="navbar-right" slot="right"><view class="dot-box right-item" @click="onPublish">发布</view></view>
		</u-navbar>

		<!-- 文本内容 -->
		<view class="push-txt wid1p padd20"><textarea placeholder="记录这一刻,分享给他人" v-model="form.contents"></textarea></view>

		<!-- 录音完成显示条 		播放录音		-->
		<view class="flex ali-cen fo-white" v-if="isRecordCompete && !showRecordBox" @click="playVoice">
			<view class="RecordAudio radius60 ml20 flex just-end ali-cen" style="background-color: skyblue; width: 400rpx;height: 100rpx;">
				<view class="mr40">
					<view v-if="!isPlayAudio_END"><text class="cuIcon-playfill"></text></view>
					<view v-else><text class="cuIcon-stop"></text></view>
				</view>
				<text class="font-wei600 mr30 fo30">{{ RecordingTime }} S</text>
			</view>
			<view class="radius50p bg-Gray padd20 yicon-xs flex just-cent ali-cen ml20"><text class="cuIcon-close fo-white" @click="onDelete('RecordAudio')"></text></view>
		</view>

		<!-- 录音组件 -->
		<view class="recordBox flex flex-col ali-cen" v-if="showRecordBox">
			<view class="">{{ RecordingTime }} s</view>
			<view class="flex ali-cen wid1p just-spa-aro">
				<view class="paddtb20 paddlr40 radius50" style="background-color: #ebebeb;" v-if="isRecordCompete" @click="onDelete"><text class="cuIcon-delete"></text></view>

				<canvas class="canvas" canvas-id="canvas">
					<!-- 录音完成后  和播放中  暂停中 -->
					<template v-if="isRecordCompete">
						<view class="flex just-cent ali-cen relative" @click="playVoice" style="margin-top: 20px;">
							<view class="SolidCircle bg-SkyBlue yicon-100 radius50p center-center" :class="{ SolidCircle_Activing: isRecording }"></view>
							<view class="CorrugatedCircle" :class="{ CorrugatedCircle_Activing: isRecording }"></view>
						</view>
					</template>
					<!-- 未录音前  和 录音中 -->
					<template v-else>
						<view class="flex just-cent ali-cen relative" @click="onRecord" style="margin-top: 20px;" v-if="!isRecordCompete">
							<view class="SolidCircle bg-SkyBlue yicon-100 radius50p center-center" :class="{ SolidCircle_Activing: isRecording }"></view>
							<view class="CorrugatedCircle" :class="{ CorrugatedCircle_Activing: isRecording }"></view>
						</view>
					</template>
				</canvas>
				<view class="paddtb20 paddlr40 radius50" style="background-color: skyblue;" v-if="isRecordCompete" @click="onCheckAutio"><text class="cuIcon-check"></text></view>
			</view>
			<view class="pb20" @click="onRecord" style="color: skyblue;">点击录音</view>
		</view>
	</view>
</template>

<script>
var timers = null;
var recorderManager = uni.getRecorderManager(); //全局唯一的录音管理器
var innerAudioContext = uni.createInnerAudioContext(); // 创建并返回内部 audio 上下文
// innerAudioContext.autoplay = true;

import {  API$GetMpUploadOssHelper, } from '../../common/API/file.js';
import { API$AddArticle,API$UploadRecord } from '../../common/API/community.js';
export default {
	name: 'PAudio',
	data() {
		return {
			background: {
				background: '#87ceeb'
			},
			text: 'uni-app',
			voicePath: null, // 录音完成地址

			form: {
				contents: '', // 发布的文字内容
				audioList: [] // 发布的图片数组 (传给后端的)
			},

			isPlayAudio: false, // 是否在音频播放中
			isPlayAudio_END: true, // 音频是否播放完成

			showRecordBox: true, // 显示录音组件
			canvasObj: null, // 画布对象
			isRecording: false, // 是否录音中
			isRecordCompete: false, // 是否录音完成
			RecordingTime: 0, // 记录时间
			// CircleRadius: 0 // 园的半径
		};
	},
	onReady() {
		// var _this = this;

		// //根据canvas 动态中心点
		// var query = uni.createSelectorQuery();
		// query.select('.canvas').boundingClientRect();
		// query.exec(function(res) {
		// 	console.log(res);
		// });
		// var query = uni.createSelectorQuery();
		// query.select('.SolidCircle').boundingClientRect();
		// query.exec(function(res) {
		// 	this.CircleRadius = res[0].width;
		// 	console.log('SolidCircle', res);
		// });
	},
	onLoad() {
		// 监听录音完成的事件
		recorderManager.onStop(res => {
			this.voicePath = res.tempFilePath;
		});
		// 监听音频播放完成的事件
		innerAudioContext.onStop(res => {
			console.log('监听音频暂停播放事件');
			this.isPlayAudio_END = true;
		});
		// 监听音频播放完成的事件
		innerAudioContext.onEnded(res => {
			console.log('监听音频自然播放完成事件');
			this.isPlayAudio_END = true;
		});
	},
	onUnload(){
		innerAudioContext.destroy()
	},
	methods: {
		// 播放/暂停
		playVoice() {
			console.log('播放录音');
			if (this.voicePath) {
				this.isPlayAudio = !this.isPlayAudio;
				if (this.isPlayAudio) {
					innerAudioContext.src = this.voicePath;
					innerAudioContext.play();
					this.isPlayAudio_END = false;
				} else {
					innerAudioContext.pause();
					this.isPlayAudio_END = true;
				}
			}
		},

		// 开始录音
		onRecord() {
			this.isRecording = !this.isRecording;
			if (!this.isRecording) {
				return this.StopRecord();
			}
			this.RecordingTime = 0
			recorderManager.start();
			timers = setInterval(() => {
				if (this.RecordingTime === 60) {
					this.StopRecord();
					return;
				}
				this.RecordingTime++;
				let ctx = uni.createCanvasContext('canvas');
				ctx.beginPath();
				ctx.setStrokeStyle('blue');
				ctx.setGlobalAlpha(1);
				ctx.setLineWidth(3);
				ctx.arc(50, 50, 28, 0, (this.RecordingTime * Math.PI) / 30);
				ctx.stroke();
				ctx.draw();
			}, 1000);
			this.isRecording = true;
		},
		// 关闭录音/删除录音
		StopRecord() {
			clearInterval(timers);
			timers = null;
			this.isRecording = false; // 当前是否在录音中
			this.ClearCanvas(); // 清空画布
			recorderManager.stop(); // 录音结束
			this.isRecordCompete = true;
		},
		// 清空画布
		ClearCanvas() {
			let ctx = uni.createCanvasContext('canvas');
			ctx.fillStyle = '#FFFFFF';
			ctx.beginPath();
			ctx.fillRect(0, 0, 200, 200);
			ctx.closePath();
			ctx.draw();
		},
		// 清空表单和实例
		clearForm(){
			this.voicePath=null, 
			this.form.contents= ''
			this.form.audioList= []
			innerAudioContext.destroy()
		},
		// 删除完成的录音
		onDelete(type) {
			this.isRecordCompete = false;
			this.voicePath = null;
			this.RecordingTime = 0;
			innerAudioContext.stop(); // 停止正在播放的录音
			type === 'RecordAudio' ? (this.showRecordBox = true) : '';
		},
		// 选中录音完成
		onCheckAutio() {
			this.showRecordBox = false;
		},
		// 上传录音文件
		async UplopadFile() {
			// 获取签名
			let { params } = await API$GetMpUploadOssHelper();
			
			let fileID = this.$tool.create_timeName();
			let key = 'uploadAudio/' + fileID + '.mp3';
			let UploadTask =  uni.uploadFile({
				url: 'https://' + params.host,
				filePath:this.voicePath,
				name: 'file',
				formData: {
					key,
					policy: params.policy,
					OSSAccessKeyId: params.OSSAccessKeyId,
					success_action_status: '200',
					Signature: params.signature
				},
				success: async uploadFileRes => {
					let {code,msg,data} = await API$UploadRecord({fileID:key,UploadType:'community',duration:this.RecordingTime})
					console.log('API$UploadRecord接口：',code,msg,data)
					if (uploadFileRes.statusCode == 200) {
						this.$pub.Toast('上传成功~');
						// 发布
						this.PushArticle({
							_id:this.$pub.getStorageSync('UserInfo')._id,
							PushType: 'audio/text',
							contents: this.form.contents,
							audioList:data
						});
					}
					if (uploadFileRes.statusCode == 413) {
						uni.showToast({
							title: '文件过大',
							icon: 'none',
							duration: 4000
						});
					}
				},
				fail: error => {
					this.$pub.Toast('上传失败~')
					console.log(error);
				},
				complete: () => {
					console.log('完成（不论成功失败~） ');
				}
			});
			UploadTask.onProgressUpdate((UploadTask_res)=>{
				uni.showLoading({ mask:true, title: '上传中：'+UploadTask_res.progress});
			})
		},
		// 发布
		onPublish() {
			// 文字 或 音频不能为空
			if(!this.form.contents && this.voicePath==null){
				return this.$pub.Toast('文字或语音不能为空！')
			}
			this.UplopadFile()
		},
		/**************************************数据处理部分*************************************/
		// 发布接口封装
		async PushArticle(json) {
			try {
				let { code, msg, data } = await API$AddArticle(json);
				console.log('API$AddArticle接口：',code,msg,data)
				if (code === 200) {
					this.clearForm();
					setTimeout(() => {
						// 本地静态添加数据到社区主页的数据列表
						uni.$emit('FreshArticleList', {
							CallType: 'addArticle',
							data
						});
						this.$pub.Toast(msg);
					}, 500);
					this.$pub.back();
				}
			} catch (e) {
				this.$pub.Toast(e)
				console.log(e)
			} finally {
				uni.hideLoading();
			}
		}
	}
};
</script>

<style scoped>
.navbar-right {
	margin-right: 24rpx;
	display: flex;
}
.right-item {
	margin: 0 12rpx;
	position: relative;
	color: #ffffff;
	display: flex;
}

/* 录音组件 */
.recordBox {
	/* position: relative; */
	position: fixed;
	bottom: 20px;
	width: 100%;
}
/* 波纹 */
.CorrugatedCircle {
	height: 120rpx;
	width: 120rpx;
	border-radius: 50%;
	background-color: rgba(135, 206, 235, 0.3);
}
/* 波纹激活中 */
.CorrugatedCircle_Activing {
	animation: CorrugatedCircle-recording 0.5s infinite linear reverse both;
}
/* 实心圆 */
.SolidCircle {
	transition: 1s;
}
/* 实心圆录音中 */
.SolidCircle_Activing {
	height: 40rpx;
	width: 40rpx;
}
/* 进度条画布 */
.canvas {
	height: 100px;
	width: 100px;
	transform: rotate(-90deg);
	/* background-color: #ffc1071f; */
}
@keyframes CorrugatedCircle-recording {
	0% {
		transform: scale(1);
		/* padding: 20rpx; */
	}
	25% {
		transform: scale(1.2);
		/* padding: 26rpx; */
	}
	50% {
		transform: scale(1.25);
		/* padding: 32rpx; */
	}
	75% {
		transform: scale(1.2);
		/* padding: 26rpx; */
	}
	100% {
		transform: scale(1);
		/* padding: 20rpx; */
	}
}
</style>
